var filename = ''
var imgArr = []

const Model = require('../../models/index'),
    Artical = Model.Artical,
    Collection = Model.Collection,
    express = require('express'),
    router = express.Router(),
    multer = require('multer'),
    fs = require('fs'),
    crypto = require('crypto'),
    storage = multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, 'assets/image')
        },
        filename: (req, file, cb) => {
            let sha1 = crypto.createHash('sha1')
            sha1.update(new Date().toISOString())
            filename = sha1.digest('hex')
            cb(null, req.session.account + '/artical/' + filename + '.png')
        }
    }),
    upload = multer({storage: storage})

router.post('/save', (req, res) => {
    let newArtical = new Artical({
        title: req.body.title,
        excerpt: req.body.excerpt,
        content: req.body.content,
        isPublish: req.body.isPublish,
        account: req.session.account,
        hot: false,
        createdTime: new Date()
    })

    // try {
    //     deleteImg(imgArr)
    // } catch (error) {

    // }

    newArtical.save((err, artical) => {
        if (err) {
            res.send({result: 'failed', error_code: 501, reason: 'when saving artical in db' })
        } else {
            res.send({result: 'success'})
        }
    })
})

router.post('/upload-image', upload.single('img'), (req, res) => {
    let imgPath = `assets/image/${req.session.account}/artical/${filename}.png`
    imgArr.push(imgPath)
    res.send({result: 'success', imgPath: imgPath})
})

router.get('/list', (req, res) => {
    Artical.find({account: req.session.account}, null, {skip: (req.body.page_index - 1) * req.body.page_size, limit: req.body.page_size}, (err, artical) => {
        if (err) {
            res.send({result: 'failed', error_code: 503, reason: 'when find artical' })
        } else {
            Artical.count({account: req.session.account}, (err, count) => {
                if (err) {
                    // todo change code
                    res.send({result: 'failed', error_code: 503, reason: 'when count artical' })
                } else {
                    res.send({result: 'success', data: artical, total: count})
                }
            })
        }
    })
})

router.get('/all', (req, res) => {
    Artical.find({isPublish: true}, null, {skip: (req.body.page_index - 1) * req.body.page_size, limit: req.body.page_size})
        .populate({path: 'info', select: 'nickname avatar -account -_id'})
        .exec((err, artical) => {
            if (err) {
                res.send({result: 'failed', error_code: 503, reason: 'when find artical' })
            } else {
                Artical.count({isPublish: true}, (err, count) => {
                    if (err) {
                        // todo change code
                        res.send({result: 'failed', error_code: 503, reason: 'when count artical' })
                    } else {
                        res.send({result: 'success', data: artical, total: count})
                    }
                })
            }
        })
})

router.get('/hot', (req, res) => {
    Artical.find({hot: true}, (err, artical) => {
        if (err) {
            res.send({result: 'failed', error_code: 503, reason: 'when find artical' })
        } else {
            res.send({result: 'success', data: artical})
        }
    })
})

router.delete('/delete', (req, res) => {
    Artical.remove({_id: req.body.aid}, (err) => {
        if (err) {
            // todo change code
            res.send({result: 'failed', error_code: 503, reason: 'when delete artical' })
        } else {
            res.send({result: 'success'})
        }
    })
})

router.get('/favor', (req, res) => {
    // collection is made of id
    Collection.find({account: req.session.account})
    .populate({
        path: 'aids',
        options: {
            limit: req.body.page_size,
            skip: (req.body.page_index - 1) * req.body.page_size
        }
    }).exec((err, collections) => {
        if (err) {
            // todo change code
            res.send({result: 'failed', error_code: 503, reason: 'when find collections' })
        } else {
            Collection.find({account: req.session.account}, (err, allCollection) => {
                if (err) {
                    // todo change code
                    res.send({result: 'failed', error_code: 503, reason: 'when find collections total' })
                } else {
                    res.send({result: 'success', data: collections, total: allCollection})
                }
            })
        }
    })
})

// router.post('/favor', (req, res) => {
//     Collection.find({account: req.session.account}, (err, collections) => {
//         if (err) {
//             // todo change code
//             res.send({result: 'failed', error_code: 503, reason: 'when find collections' })
//         } else {
//             console.log(collections)
//         }
//     })
// })

router.put('/is-publish', (req, res) => {
    Artical.findOneAndUpdate({_id: req.body.aid}, {$set: {isPublish: req.body.isPublish}}, (err) => {
        if (err) {
            // todo change code
            res.send({result: 'failed', error_code: 503, reason: 'when update is-publish status' })
        } else {
            res.send({result: 'success'})
        }
    })
})

router.put('/is-collect', (req, res) => {
    if (req.body.isCollect) {
        Collection.findOneAndUpdate({account: req.session.account}, {$push: {aids: req.body.aid}}, (err) => {
            if (err) {
                // todo change code
                res.send({result: 'failed', error_code: 503, reason: 'when update is-collect status' })
            } else {
                Artical.findOneAndUpdate({_id: req.body.aid}, {'$inc': {likeNum: 1}}, (err) => {
                    if (err) {
                        // todo change code
                        res.send({result: 'failed', error_code: 503, reason: 'when increase like number' })
                    } else {
                        res.send({result: 'success'})
                    }
                })
            }
        })
    } else {
        Collection.findOneAndUpdate({account: req.session.account}, {$pull: {aids: req.body.aid}}, (err) => {
            if (err) {
                // todo change code
                res.send({result: 'failed', error_code: 503, reason: 'when update is-collect status' })
            } else {
                Artical.findOneAndUpdate({_id: req.body.aid, likeNum: { $gte: 1 }}, {'$inc': {likeNum: -1}}, (err) => {
                    if (err) {
                        // todo change code
                        res.send({result: 'failed', error_code: 503, reason: 'when update is-collect status' })
                    } else {
                        res.send({result: 'success'})
                    }
                })
            }
        })
        // -1 但是却大于 0
    }
    // Collection.
})

function deleteImg (imgURLArr, safeImgURL) {
    imgURLArr.forEach(function (e, index) {
        if (safeImgURL.indexOf(e) == -1) {
            fs.unlink(e, function (err) {
                if (err) {
                    throw err
                }
            })
        }
    })
}

module.exports = router
